var notify_url = 'https:/beautycafe.club/order/returnPay'
var spbill_create_ip = '123.12.12.123'
var trade_type = 'JSAPI'
var paykey = '6289384392e39fe85938d7bd7b43ff48'
var appid = 'wx402d332ba0f06174'
var mch_id = '1514595541'
var md5 = require('md5')
var request = require('request')
var xml2js = require('xml2js')
var fs = require('fs')
module.exports.generateParam =  function generateParam(openid, out_trade_no,total_fee,body){
	var params = {}
	params.openid = openid
	params.out_trade_no = out_trade_no
	params.total_fee = String(total_fee)
	params.body = body
	params.notify_url = notify_url
	params.spbill_create_ip = spbill_create_ip
	params.appid = appid
	params.mch_id = mch_id
	params.trade_type = trade_type
	params.nonce_str = randomNonce_str()
	var keys = Object.keys(params).sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
		})
    var paramsStr = ''
    for (var i = 0 ; i < keys.length;i++){
    	
    	var x = keys[i]
    	paramsStr += x + '='+params[x] + '&'
    	
    }
    paramsStr += "key=" + paykey
    var sign=md5(paramsStr).toUpperCase()
    params.sign = sign
     keys = Object.keys(params).sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});
    var xml = '<xml>'
     for (var i = 0 ; i < keys.length;i++){
    	
    	var x = keys[i]
    	xml += '<' + x + '>'+params[x] + '</' + x + '>'
    	
    }   
    xml += '</xml>'
    return [xml,params]

}


module.exports.wxPay = function wxPay(xml,callback){
		request({
		 	url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
		 	method: "POST",
		 	timeout: 10000,
		 	followRedirect: true,
		 	maxRedirects: 10,
		 	body : xml
		 },function(error, response, body){
			////console.log(error,'hey eroro')
		 	////console.log(response,'jey ')
		 	xml2js.parseString(body,function(err,result){
		 		callback(error,response,result.xml)
		 	})
		 	
		 })
}

module.exports.payParam = function payParamGenerator(parsedBody){
	var timeStamp = String(new Date().getTime())
	var payStr = 'appId=' + appid + '&nonceStr=' + parsedBody['nonce_str'][0] + '&package=prepay_id=' + parsedBody['prepay_id'] + '&signType=MD5' 
			+ '&timeStamp=' + timeStamp + '&key=' + paykey
	var paySign = md5(payStr)
	var finalpayparam = {}
	finalpayparam.paySign = paySign
	finalpayparam.package = 'prepay_id=' + parsedBody.prepay_id[0]
	finalpayparam.nonceStr = parsedBody.nonce_str[0]
	finalpayparam.timeStamp = timeStamp
	return finalpayparam
}


module.exports.reimburse = function reimburse(out_refund_no,out_trade_no,refund_fee,total_fee,callback){
	//refund_fee = 1
	//total_fee = 1
	var nonce_str = randomNonce_str()
	var bodyData = '<xml>';
    bodyData += '<appid>' + appid + '</appid>';
    bodyData += '<mch_id>' + mch_id + '</mch_id>';
    bodyData += '<nonce_str>' + nonce_str + '</nonce_str>';
    bodyData += '<op_user_id>' + mch_id + '</op_user_id>';
    bodyData += '<out_refund_no>' + nonce_str + '</out_refund_no>';
    bodyData += '<out_trade_no>' + out_trade_no + '</out_trade_no>';
    bodyData += '<refund_fee>' + refund_fee + '</refund_fee>';
    bodyData += '<sign_type>MD5</sign_type>'
    bodyData += '<total_fee>' + total_fee + '</total_fee>';

    var results = refundOrderSign(
        appid,
        mch_id,
        nonce_str,
        mch_id,
        out_refund_no, // 商户退款单号 给一个随机字符串即可out_refund_no 
        out_trade_no,
        refund_fee,
        total_fee
    );
    xml = results[0]
    sign = results[1]
    bodyData += '<sign>' + sign + '</sign>';
    bodyData += '</xml>';
    var agentOptions = {
        pfx: fs.readFileSync('./util/apiclient_cert.p12'),
        passphrase: mch_id,
    };

    var urlStr = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
    request({
        url: urlStr,
        method: 'POST',
        body: xml,
        agentOptions: agentOptions
    }, function (error, response, body) {
    	xml2js.parseString(body,function(err,result){
		 		callback(error,response,result.xml)
		 	})
       
    })




}

function randomNonce_str(){
		var xxx = Math.random() * 1000
		return md5(String(xxx))
}

function refundOrderSign(appid,mch_id,nonce_str,op_user_id,out_refund_no,out_trade_no,refund_fee,total_fee) {
    var ret = {
        appid: appid,
        mch_id: mch_id,
        nonce_str: nonce_str,
        op_user_id: op_user_id,
        out_refund_no: out_refund_no,
        out_trade_no: out_trade_no,
        refund_fee: String(refund_fee),
        total_fee: String(total_fee)
    };
    var keys = Object.keys(ret).sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
		})
    var paramsStr = ''
    for (var i = 0 ; i < keys.length;i++){
    	
    	var x = keys[i]
    	paramsStr += x + '='+ret[x] + '&'
    	
    }
    paramsStr = paramsStr + 'key='+paykey;

    var md5Str = md5(paramsStr)
    md5Str = md5Str.toUpperCase();

    var params = {}
	params.appid = appid
	params.mch_id = mch_id
	params.total_fee = String(total_fee)
	params.nonce_str = nonce_str
	params.op_user_id = mch_id
	params.out_refund_no = out_refund_no
	params.out_trade_no = out_trade_no
	params.mch_id = mch_id
	params.refund_fee = refund_fee
	var keys = Object.keys(params).sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
		})
    var paramsStr = ''
    for (var i = 0 ; i < keys.length;i++){
    	
    	var x = keys[i]
    	paramsStr += x + '='+params[x] + '&'
    	
    }
    paramsStr += "key=" + paykey
    var sign=md5(paramsStr).toUpperCase()
    params.sign = sign
     keys = Object.keys(params).sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});
    var xml = '<xml>'
     for (var i = 0 ; i < keys.length;i++){
    	
    	var x = keys[i]
    	xml += '<' + x + '>'+params[x] + '</' + x + '>'
    	
    }   
    xml += '</xml>'


    return [xml,sign];

}